const express = require('express');

const routes = express.Router();

//引入mysql
const mysql = require('mysql');

//引入util模块
var util = require('util');
//创建连接池
var pool = mysql.createPool({
    connectionLimit : 10,
    host : 'localhost',
    user : 'root',
    password : 'root',
    database : 'stumsg'
})

routes.route('/')
    .get( (req,resp)=>{

        //获取cookies
        var uid = req.cookies.uid;
        var gender = req.cookies.gender;
        //获取教师专业号
        var tea_uid = req.cookies.sub_id;
        //获取学生的学号
        var stu_uid = req.query.uid;
        //console.log(tea_uid)
        //判断
        if(gender == 1){
            var pname = '教师';
        }else {
            var pname = '学生';

        }
        //sql语句
        var sql = `SELECT stu_list.* FROM stu_list WHERE stu_list.uid = ${stu_uid} AND stu_list.sub_id = ${tea_uid}`;
        //    执行sql语句
    pool.getConnection( (err , connection)=>{
        if (err) throw err;
        connection.query( sql, (error , result)=>{
            //    释放连接
            connection.release();
            //
            //console.log(result)
            resp.render('stu_update',{
                uid : uid,
                pname : pname,
                tea_uid : tea_uid,
                result : result
            })

            if(error) throw error;
        } )
    } )

    } )
//模块化路由
//查询当前学期的全部课程
.post((req,resp)=>{
    //console.log(req.body)
    //    提起修改过来的数据
    //    学生学号
    var uid = req.body.uid;
    var stu_name = req.body.stu_name.trim();
    var gender = parseInt(req.body.gender);
    var tmp = req.body.birtmp;
    //将字符串时间转换为时间戳
    var birtmp = new Date(tmp).getTime();
    //var sub_id = parseInt(req.body.sub_id);  sub_id = ${sub_id},
    var intro = req.body.intro;
    //获取当前的系统时间戳
    var dat = new Date().getTime();
    //console.log(dat)
    //提取当前时间戳的年份
    var year = new Date(dat).getFullYear();
    //console.log(year)
    //选择器的的年份
    var newtmp = new Date(birtmp).getFullYear();
    //console.log(newtmp)
    //两个年份相减
    var age = parseInt(year - newtmp);
    //console.log( uid ,  stu_name , gender , birtmp , sub_id , intro )
    //    sql语句
    var sql = `UPDATE stu_list SET stu_name = '${stu_name}',gender = ${gender}, birtmp = ${birtmp}, intro = '${intro}',age = ${age} WHERE uid = ${uid}`;
    //console.log(sql)
    //    执行sql语句
    pool.getConnection( (err , connection)=>{
        if (err) throw err;
        connection.query( sql, (error , result)=>{
            //    释放连接
            connection.release();

           if(result){
               resp.redirect('/sel_list')
           }

            if(error) throw error;
        } )
    } )
} )


//暴露接口
module.exports = routes;